package ru.housewife.service.dishes;

import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.form.CookingDishRecipeForm;
import ru.housewife.form.UserForm;
import ru.housewife.model.CookingDishRecipe;
import ru.housewife.model.CookingDishRecipeGroup;
import ru.housewife.model.User;

/**
 * Adds new cooking dish recipe.
 *
 * @author Alexander Troshanin
 */
public class AddNewCookingDishRecipe implements HibernateAction<CookingDishRecipe> {

    private CookingDishRecipeForm recipeForm;
    private UserForm userForm;

    public AddNewCookingDishRecipe(UserForm userForm, CookingDishRecipeForm recipeForm) {
        this.userForm = userForm;
        this.recipeForm = recipeForm;
    }

    @Override
    public CookingDishRecipe execute(Session session) {
        User user = (User) session.get(User.class, userForm.getId());
        if (user == null) {
            return null;
        }
        CookingDishRecipeGroup group = (CookingDishRecipeGroup) session.get(CookingDishRecipeGroup.class, recipeForm.getGroup().getId());
        if (group == null) {
            return null;
        }

        CookingDishRecipe recipe = new CookingDishRecipe();

        recipe.setName(recipeForm.getName());
        recipe.setSingleComponent(recipeForm.isSingleComponent());
        recipe.setWayToPrepare(recipeForm.getWayToPrepare());
        recipe.setRecipesGroup(group);
        recipe.setOwner(user);

        session.save(recipe);
        recipeForm.setId(recipe.getId());

        DishHiberUtils.addNewComponentsToRecipe(session, recipe, recipeForm.getComponents());

        session.save(recipe);

        recipeForm = new CookingDishRecipeForm(recipe);
        userForm.addUserRecipe(recipeForm);
        
        return recipe;
    }

}
